package com.fatesgo.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fatesgo.mapper.UserMapper;
import com.fatesgo.pojo.User;
import com.fatesgo.service.ILoginService;
import com.fatesgo.util.JwtUtil;
import com.fatesgo.util.RedisUtil;
import com.fatesgo.util.Response;

@Service
public class ILoginServiceImpl implements ILoginService {


    @Autowired
    RedisUtil redisUtil;

    @Autowired(required = false)
    private UserMapper userMapper;

    @Override
    public Response login(String userName, String password) {
        // @formatter:off
        User user = userMapper.login(userName, password);
        if (user == null) return Response.error("账号或者密码错误！");

        System.out.println(JSONObject.toJSON(user));

        // 生成签名
        String token = JwtUtil.sign(user.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        redisUtil.set("user_info" + token, user, 1800);
        redisUtil.set("user_token" + user.getId().toString(), token, 1800);

        return Response.success(token, map);
        // @formatter:on
    }

    @Override
    public Response logout(String token,String userId) {
        try {
            // 从 Redis 中删除用户信息
            redisUtil.del("user_info" + token);
            // 从 Redis 中删除用户令牌
            redisUtil.del("user_token" + userId);
            return Response.success("成功退出登录");
        } catch (Exception e) {
            e.printStackTrace();
            return Response.error("退出登录失败");
        }
    }
}
